<template>
  <div class="search-result-container">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell 
        v-for="(result,index) in resultList" 
        :key="index" 
        :title="result.title" 
        :to="{
          name:'Article',
          params:{
            articleId: result.art_id
          }
        }"   
        />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'
export default {
  name: "SearchResult",
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data() {
    return {
      resultList: [],
      loading: false,
      finished: false,
      page: 1 ,
      per_page: 20
    };
  },

  mounted() {
    // this.loadSearchResult()
  },

  methods: {
      async onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // setTimeout(() => {
      //   for (let i = 0; i < 10; i++) {
      //     this.list.push(this.list.length + 1);
      //   }

      //   // 加载状态结束
      //   this.loading = false;

      //   // 数据全部加载完成
      //   if (this.list.length >= 40) {
      //     this.finished = true;
      //   }
      // }, 1000);
      let params = {
        q: this.searchText,
        page: this.page,
        per_page: this.per_page
      }
      const {data:{data:{results}}} = await getSearchResult(params)
      this.resultList.push(...results)
      this.loading = false;
      // 判断数据是否有加载完成
      if (results.length === 0) {
        this.finished = true
      }else{
        this.page++
      }
    },
  },
};
</script>

<style lang="less" scoped>
</style>